# 在你的 forms.py 文件中创建表单
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser, StudentProfile, TeacherProfile, CaptchaModel


class StudentSignUpForm(UserCreationForm):

    email = forms.EmailField(error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确',
    })
    password = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '密码不能为空',
        'max_length': '密码长度不能超过20',
        'min_length': '密码长度不能小于6',
    })
    captcha = forms.CharField(max_length=6, min_length=6, error_messages={
        'required': '验证码不能为空',
        'max_length': '验证码长度不能超过6',
        'min_length': '验证码长度不能小于6',
    })

    # 校验邮箱是否已存在
    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = StudentProfile.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('邮箱已存在')
        else:
            return email
    # 验证验证码
    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha')
        email = self.cleaned_data.get('email')
        captcha_model = CaptchaModel.objects.filter(email=email, captcha=str(captcha)).first()
        if not captcha_model:
            raise forms.ValidationError('验证码错误')
        else:
            captcha_model.delete()
            return captcha


class TeacherSignUpForm(UserCreationForm):
    teacher_id = forms.CharField(max_length=20)

    class Meta:
        model = CustomUser
        fields = ('username', 'teacher_id', 'password1', 'password2')

    def save(self, commit=True):
        user = super().save(commit=False)
        user.is_teacher = True
        if commit:
            user.save()
            TeacherProfile.objects.create(user=user, teacher_id=self.cleaned_data['teacher_id'])
        return user
